import React from 'react';
import { Select } from 'antd';

const { Option } = Select;

class SubSelect extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if ('value' in nextProps) {
      return { value: nextProps.value };
    }
    return null;
  }

  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
    };
  }

  componentDidMount() {
    this.getData(this.props);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.parentValue !== this.props.parentValue) {
      this.getData(this.props);
    }
  }

  getData(props) {
    const { options, parentValue } = props;
    if (!(options && options[parentValue]) && parentValue) {
      this.props.getData(parentValue);
    }
  }

  handleChange = value => {
    if (!('value' in this.props)) {
      this.setState({ value });
    }
    this.triggerChange(value);
  };

  triggerChange = changedValue => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { value } = this.state;
    const {
      parentValue,
      renderOption,
      options,
      placeholder,
      ...others
    } = this.props;
    return (
      <Select {...others} value={value || 0} onChange={this.handleChange}>
        <Option value={0}>{placeholder || '未选择'}</Option>
        {options && options[parentValue] && options[parentValue].length > 0 ? (
          options[parentValue].map(renderOption(Option))
        ) : (
          <Option value={1} disabled>
            暂无数据
          </Option>
        )}
      </Select>
    );
  }
}

export default SubSelect;
